package com.huang.readwriteLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.StampedLock;

/*
*           少用   容易导致死锁  不可重入   不能中断
*                       发现读的时候写操作改了数据  将锁改成悲观读锁
*
* */
public class StampedLockDemo {
   static int num=10;
    public static void main(String[] args) {
        StampedLock stampedLock = new StampedLock();
        long l = stampedLock.tryOptimisticRead();//票据
        //读
        new  Thread(()->{

            try {
                stampedLock.readLock();
                System.out.println(stampedLock.validate(l));

                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if(!stampedLock.validate(l)){
                 stampedLock.readLock();//  有人动过换回 悲观读  重新获取num值  之前的作废 不允许读的时候 进行写操作了

                    System.out.println("有人动过。。。"+stampedLock.validate(l)+"num为:"+num);

                }
            } finally {
                stampedLock.unlockRead(l);
            }

        }).start();

        new Thread(()->{
            try {
                stampedLock.writeLock();
                for (int i = 0; i < 3; i++) {
                    num++;
                }
            } finally {
                stampedLock.unlockWrite(l);
            }

        }).start();


    }
}
